import QtQuick
import QtQuick.Controls
import QtQuick.Layouts

Item {
    id: uDisk_MaterialListBack_ListWindow
    width: 1760
    height: 935

    property real fontSize: Cpp_Language.CurrentLanguage === 1 ? 20 : Cpp_Language.CurrentLanguage === 2 ? 13 : Cpp_Language.CurrentLanguage === 3 ? 13 : 20


    property bool plc_M61: Cpp_PLC.M_61
    property bool plc_M96: Cpp_PLC.M_96
    property bool plc_M97: Cpp_PLC.M_97
    property bool plc_X13: Cpp_PLC.X13

    Component.onCompleted: {
        Cpp_PLC.write_into_PLC_16_Hold(48,"3")
        Cpp_PLC.write_into_PLC_Coils(142,true)
    }


    A_NumberKeyboard{
        id: uDiskMaterialListKeyboard
        isDirectOverwrite: false
    }

    Row {
        anchors.top: parent.top
        anchors.left: parent.left
        height: 50

        // 12个标题项（宽度总和=1500，精确计算）
        TitleItem { title: qsTr("序号"); itemWidth: 90 }        // 1
        TitleItem { title: qsTr("材料名称"); itemWidth: 150 }   // 2
        TitleItem { title: qsTr("颜色"); itemWidth: 90 }         // 3
        TitleItem { title: qsTr("ID"); itemWidth: 90 }           // 4
        TitleItem { title: qsTr("规格型号"); itemWidth: 160 }   // 5
        TitleItem { title: qsTr("切割长度"); itemWidth: 160 }   // 6
        TitleItem { title: qsTr("左角度"); itemWidth: 120 }     // 7
        TitleItem { title: qsTr("右角度"); itemWidth: 120 }     // 8
        TitleItem { title: qsTr("原料长度"); itemWidth: 130 }   // 9
        TitleItem { title: qsTr("剩余长度"); itemWidth: 130 }   // 10
        TitleItem { title: qsTr("总数量"); itemWidth: 130 }     // 11
        TitleItem { title: qsTr("已切数量"); itemWidth: 130 }   // 12
    }

    // 标题项组件（统一样式与布局）
    component TitleItem: Rectangle {
        property string title: ""       // 标题文本
        property real itemWidth: 100    // 单项宽度

        width: itemWidth
        height: parent.height  // 高度与容器一致（80）
        color: "#eeeeee"       // 标题项背景（略深于总背景）
        border.width: 0.5
        border.color: "#ddd"


        // 标题文字（自动适应宽度，防止溢出）
        Text {
            anchors.centerIn: parent
            text: title
            font.pixelSize: fontSize  // 适中字号，平衡显示与空间
            font.bold: true
            color: "#333"
            elide: Text.ElideRight  // 极端情况文字过长时省略尾部
            maximumLineCount: 1    // 强制单行显示
        }
    }

    // 表格项目
    ListView {
        id: materialListView
        anchors.top: parent.top
        anchors.topMargin: 50
        width: 1500
        height: 880
        model: usbCutDataModel  // 绑定usbCutDataModel单例
        clip: true
        boundsBehavior: Flickable.StopAtBounds

        // 检查当前行是否完成（总数量=已加工数量）
        function checkComplete(rowIndex) {
            if (rowIndex < 0 || rowIndex >= usbCutDataModel.rowCount()) return false;
            const item = usbCutDataModel.get(rowIndex);  // 调用usbCutDataModel的get方法
            return item.totalCount === item.processedCount && item.totalCount !== 0;
        }

        // 查找下一个未完成的行
        function findNextValidRow(startIndex) {
            for (let i = startIndex + 1; i < usbCutDataModel.rowCount(); i++) {
                if (!checkComplete(i)) {
                    return i;
                }
            }
            return -1;
        }

        // 自动移动到下一个有效行
        function moveToNextValidRow(currentIndex) {
            const nextIndex = findNextValidRow(currentIndex);
            if (nextIndex !== -1) {
                materialListView.currentIndex = nextIndex;
                console.log("自动跳过已完成行，移动到第" + (nextIndex + 1) + "行");
            } else {
                materialListView.currentIndex = -1;
                console.log("后续无有效行，取消选中");
                checkAndShowCompletionDialog();
            }
        }

        // 检查所有行是否都已完成
        function checkAllComplete() {
            const model = usbCutDataModel;
            if (model.rowCount() === 0) return false;
            for (let i = 0; i < model.rowCount(); i++) {
                if (!checkComplete(i)) {
                    return false;
                }
            }
            return true;
        }

        delegate: Item {
            width: materialListView.width
            height: 44
            // 绑定usbCutDataModel的属性
            property int currentProcessedCount: processedCount
            property int currentTotalCount: totalCount
            property int currentIndex: index

            // 监听已加工数量变化
            onCurrentProcessedCountChanged: {
                checkCompletion();
            }

            // 监听总数量变化
            onCurrentTotalCountChanged: {
                checkCompletion();
            }

            // 检查完成逻辑
            function checkCompletion() {
                if (currentTotalCount === currentProcessedCount && currentTotalCount !== 0) {
                    console.log("第" + (currentIndex + 1) + "行已完成");
                    if (materialListView.currentIndex === currentIndex) {
                        if (autoWrapEnabled) {  // 假设存在自动换行开关
                            materialListView.moveToNextValidRow(currentIndex);
                        } else {
                            console.log("自动换行已禁用，保持当前选中状态");
                        }
                    }
                    materialListView.checkAndShowCompletionDialog();
                }
            }

            Row {
                id: dataRow
                height: parent.height

                // 序号列
                Rectangle {
                    width: 90
                    height: parent.height
                    color: (currentTotalCount === currentProcessedCount && currentTotalCount !== 0) ? "#ffcccc"
                        : (materialListView.currentIndex === currentIndex ? "gold" : "white")
                    border.color: "#eeeeee"
                    Text {
                        anchors.centerIn: parent
                        text: (currentIndex + 1)
                        font.pixelSize: 15
                        elide: Text.ElideRight
                        width: parent.width - 8
                        horizontalAlignment: Text.AlignHCenter
                    }
                }

                // 材料名称列
                Rectangle {
                    width: 150
                    height: parent.height
                    color: (currentTotalCount === currentProcessedCount && currentTotalCount !== 0) ? "#ffcccc"
                                                                                                    : (materialListView.currentIndex === currentIndex ? "gold" : "white")
                    border.color: "#eeeeee"
                    Text {
                        anchors.centerIn: parent
                        text: materialName
                        font.pixelSize: 15
                        elide: Text.ElideRight
                        width: parent.width - 8
                        horizontalAlignment: Text.AlignHCenter
                    }
                }

                // 颜色列
                Rectangle {
                    width: 90
                    height: parent.height
                    color: (currentTotalCount === currentProcessedCount && currentTotalCount !== 0) ? "#ffcccc"
                                                                                                    : (materialListView.currentIndex === currentIndex ? "gold" : "white")
                    border.color: "#eeeeee"
                    Text {
                        anchors.centerIn: parent
                        text: material_Color
                        font.pixelSize: 15
                        elide: Text.ElideRight
                        width: parent.width - 8
                        horizontalAlignment: Text.AlignHCenter
                    }
                }

                // 材料ID列
                Rectangle {
                    width: 90
                    height: parent.height
                    color: (currentTotalCount === currentProcessedCount && currentTotalCount !== 0) ? "#ffcccc"
                                                                                                    : (materialListView.currentIndex === currentIndex ? "gold" : "white")
                    border.color: "#eeeeee"
                    Text {
                        anchors.centerIn: parent
                        text: material_ID
                        font.pixelSize: 15
                        elide: Text.ElideRight
                        width: parent.width - 8
                        horizontalAlignment: Text.AlignHCenter
                    }
                }

                // 规格型号列
                Rectangle {
                    width: 160
                    height: parent.height
                    color: (currentTotalCount === currentProcessedCount && currentTotalCount !== 0) ? "#ffcccc"
                                                                                                    : (materialListView.currentIndex === currentIndex ? "gold" : "white")
                    border.color: "#eeeeee"
                    Text {
                        anchors.centerIn: parent
                        text: specification
                        font.pixelSize: 15
                        elide: Text.ElideRight
                        width: parent.width - 8
                        horizontalAlignment: Text.AlignHCenter
                    }
                }

                // 切割长度列
                Rectangle {
                    width: 160
                    height: parent.height
                    color: (currentTotalCount === currentProcessedCount && currentTotalCount !== 0) ? "#ffcccc"
                                                                                                    : (materialListView.currentIndex === currentIndex ? "gold" : "white")
                    border.color: "#eeeeee"
                    Text {
                        anchors.centerIn: parent
                        text: cuttingLength
                        font.pixelSize: 15
                        elide: Text.ElideRight
                        width: parent.width - 8
                        horizontalAlignment: Text.AlignHCenter
                    }
                }

                // 左角度列
                Rectangle {
                    width: 120
                    height: parent.height
                    color: (currentTotalCount === currentProcessedCount && currentTotalCount !== 0) ? "#ffcccc"
                                                                                                    : (materialListView.currentIndex === currentIndex ? "gold" : "white")
                    border.color: "#eeeeee"
                    Text {
                        anchors.centerIn: parent
                        text: leftAngle + "°"
                        font.pixelSize: 15
                        elide: Text.ElideRight
                        width: parent.width - 8
                        horizontalAlignment: Text.AlignHCenter
                    }
                }

                // 右角度列
                Rectangle {
                    width: 120
                    height: parent.height
                    color: (currentTotalCount === currentProcessedCount && currentTotalCount !== 0) ? "#ffcccc"
                                                                                                    : (materialListView.currentIndex === currentIndex ? "gold" : "white")
                    border.color: "#eeeeee"
                    Text {
                        anchors.centerIn: parent
                        text: rightAngle + "°"
                        font.pixelSize: 15
                        elide: Text.ElideRight
                        width: parent.width - 8
                        horizontalAlignment: Text.AlignHCenter
                    }
                }

                // 原料长度列
                Rectangle {
                    width: 130
                    height: parent.height
                    color: (currentTotalCount === currentProcessedCount && currentTotalCount !== 0) ? "#ffcccc"
                                                                                                    : (materialListView.currentIndex === currentIndex ? "gold" : "white")
                    border.color: "#eeeeee"
                    Text {
                        anchors.centerIn: parent
                        text: rawMaterialLength
                        font.pixelSize: 15
                        elide: Text.ElideRight
                        width: parent.width - 8
                        horizontalAlignment: Text.AlignHCenter
                    }
                }

                // 剩余长度列
                Rectangle {
                    width: 130
                    height: parent.height
                    color: (currentTotalCount === currentProcessedCount && currentTotalCount !== 0) ? "#ffcccc"
                                                                                                    : (materialListView.currentIndex === currentIndex ? "gold" : "white")
                    border.color: "#eeeeee"
                    Text {
                        anchors.centerIn: parent
                        text: remainingLength
                        font.pixelSize: 15
                        elide: Text.ElideRight
                        width: parent.width - 8
                        horizontalAlignment: Text.AlignHCenter
                    }
                }

                // 总数量列
                Rectangle {
                    width: 130
                    height: parent.height
                    color: (currentTotalCount === currentProcessedCount && currentTotalCount !== 0) ? "#ffcccc"
                                                                                                    : (materialListView.currentIndex === currentIndex ? "gold" : "white")
                    border.color: "#eeeeee"
                    Text {
                        anchors.centerIn: parent
                        text: currentTotalCount
                        font.pixelSize: 15
                        elide: Text.ElideRight
                        width: parent.width - 8
                        horizontalAlignment: Text.AlignHCenter
                    }
                }

                // 已加工数量列
                Rectangle {
                    width: 130
                    height: parent.height
                    color: (currentTotalCount === currentProcessedCount && currentTotalCount !== 0) ? "#ffcccc"
                                                                                                    : (materialListView.currentIndex === currentIndex ? "gold" : "white")
                    border.color: "#eeeeee"
                    Text {
                        anchors.centerIn: parent
                        text: currentProcessedCount
                        font.pixelSize: 15
                        elide: Text.ElideRight
                        width: parent.width - 8
                        horizontalAlignment: Text.AlignHCenter
                    }
                }
            }

            MouseArea {
                width: dataRow.width
                height: dataRow.height
                onClicked: {

                    Cpp_PLC.write_into_PLC_Coils(142,true)

                    // 已完成行不允许选中
                    if (!materialListView.checkComplete(currentIndex)) {
                        materialListView.currentIndex = currentIndex;
                        console.log("选中第" + (currentIndex + 1) + "行");
                    } else {
                        console.log("第" + (currentIndex + 1) + "行已完成，不允许选中");
                    }
                    if (currentIndex >= 0 && currentIndex < usbCutDataModel.rowCount()) {
                        const currentItem = usbCutDataModel.get(currentIndex);
                        console.log("ListView换行，当前选中第" + (currentIndex + 1) + "行，执行PLC写入指令");

                        // 适配usbCutDataModel的属性（切割长度、角度等）
                        console.log("写入 切割长度: "+currentItem.cuttingLength + " 左角度: "+currentItem.leftAngle +
                                    " 右角度: "+currentItem.rightAngle +" 总数量: "+currentItem.totalCount)


                        // 切割长度处理（根据实际业务调整）
                        if(Number(currentItem.cuttingLength) < Number(Cpp_PLC.ExtraShort_MaterialLengthMin)) {
                            Cpp_PLC.write_into_PLC_32_Hold(1440, Cpp_PLC.ExtraShort_MaterialLengthMin)
                        } else if(Number(currentItem.cuttingLength) > Number(Cpp_PLC.ExtraLong_MaterialLengthMax)) {
                            Cpp_PLC.write_into_PLC_32_Hold(1440, Cpp_PLC.ExtraLong_MaterialLengthMax)
                        } else {
                            Cpp_PLC.write_into_PLC_32_Hold(1440, currentItem.cuttingLength)
                        }

                        // Cpp_PLC.write_into_PLC_32_Hold(1440, currentItem.cuttingLength)

                        // 左角度处理（根据实际业务调整）
                        if(currentItem.leftAngle === "45") {  // usbCutDataModel中角度为QString类型
                            Cpp_PLC.write_into_PLC_16_Hold(1520,"0");
                        } else if(currentItem.leftAngle === "90") {
                            Cpp_PLC.write_into_PLC_16_Hold(1520,"1");
                        }

                        // 右角度处理（根据实际业务调整）
                        if(currentItem.rightAngle === "45") {
                            Cpp_PLC.write_into_PLC_16_Hold(1521,"0");
                        } else if(currentItem.rightAngle === "90") {
                            Cpp_PLC.write_into_PLC_16_Hold(1521,"1");
                        }

                        // 总数量写入
                        Cpp_PLC.write_into_PLC_16_Hold(1480, currentItem.totalCount)
                        // 当前数量写入 D66
                        Cpp_PLC.write_into_PLC_16_Hold(66,currentItem.totalCount)
                        // 当前已加工数量 写入 D231
                        Cpp_PLC.write_into_PLC_16_Hold(231,currentItem.processedCount)

                        // 其他PLC控制指令（保持原有逻辑）
                        Cpp_PLC.write_into_PLC_16_Hold(76,"1")
                        if(Cpp_PLC.MechineChangeAngleMode) {
                            Cpp_PLC.write_into_PLC_Coils(140,true)
                            // Cpp_PLC.write_into_PLC_Coils(141,1)
                        } else {
                            Cpp_PLC.write_into_PLC_Coils(140,true)
                            // Cpp_PLC.write_into_PLC_Coils(141,1)
                            Cpp_PLC.write_into_PLC_Coils(140,false)
                            // Cpp_PLC.write_into_PLC_Coils(141,0)
                        }

                    } else {
                        console.log("无有效选中项，不执行PLC写入");
                    }
                }
            }
        }

        // 滚动条
        ScrollBar.vertical: ScrollBar {
            policy: ScrollBar.AlwaysOn
            // width: 10
            anchors.top: parent.top
            anchors.bottom: parent.bottom
            anchors.right: parent.right
        }

        // 监听模型数据更新，重置选中状态
        Connections {
            target: usbCutDataModel
            function onModelDataUpdated() {
                materialListView.currentIndex = -1;
                console.log("材料模型数据已更新，取消选中状态（currentIndex = -1）");
            }
        }


    }

    onPlc_X13Changed: {
        if((plc_M96 && plc_X13) || (plc_M97 && plc_X13))
        {
            //计数+1
            // console.log("计数加1！！！！！")
            const isComplete = materialListView.checkComplete(materialListView.currentIndex);
            if (isComplete) {
                console.log("第" + (materialListView.currentIndex + 1) + "行已完成，不更新已切数量");
                return;
            }
            usbCutDataModel.incrementWorkedCount(materialListView.currentIndex);
            var updatedItem = usbCutDataModel.get(materialListView.currentIndex);
            console.log("已更新第" + (materialListView.currentIndex + 1) + "项，已切数量：" + updatedItem.workedCount);
            // materialListView.checkAndShowCompletionDialog();
        }
        else
        {
            console.log("无有效选中项，不更新已切数量");
        }
    }

    onPlc_M61Changed: {
        if(plc_M61)
        {
            const isComplete = materialListView.checkComplete(materialListView.currentIndex);
            if (isComplete) {
                console.log("第" + (materialListView.currentIndex + 1) + "行已完成，不更新已切数量");
                return;
            }
            usbCutDataModel.incrementWorkedCount(materialListView.currentIndex);
            var updatedItem = usbCutDataModel.get(materialListView.currentIndex);
            console.log("已更新第" + (materialListView.currentIndex + 1) + "项，已切数量：" + updatedItem.workedCount);
        }
    }






    A_ComboBox{
        anchors.top: parent.top
        anchors.topMargin: 50
        anchors.right: parent.right
        comboBoxWidth: 240
        model: usbCutDataModel.fileList
        onCurrentTextChanged:
        {
            usbCutDataModel.currentFile = currentText
            console.log("当前解析文件: " + currentText)
            usbCutDataModel.parseSelectedFile()
        }
        onComboBoxPressed: {
            usbCutDataModel.scanFiles()
        }

    }

    Column{
        anchors.top: parent.top
        anchors.topMargin: 300
        anchors.right: parent.right

        spacing: 10


        Rectangle{
            width: 250
            height: 50
            // border.width: 1
            color: "transparent"
            visible: !Cpp_PLC.M_394
            Text {
                font.pixelSize: Cpp_Language.CurrentLanguage === 1 ? 40 : Cpp_Language.CurrentLanguage === 2 ? 25 : Cpp_Language.CurrentLanguage === 3 ? 25 : 40
                anchors.centerIn: parent
                text: qsTr("料 高")
            }
        }

        A_NumberInput{
            inputWidth: 250
            inputHeight: 80
            text: Cpp_PLC.MaterialHeight_NormalProcess
            visible: !Cpp_PLC.M_394
            keyboard: uDiskMaterialListKeyboard
            onEditingFinished: function(value){
                Cpp_PLC.write_into_PLC_32_Hold(214,value);
            }
        }

        Item{
            width: 1
            height: 10
        }

        A_Button{
            buttonWidth: 250
            buttonHeight: 80
            contentText_Data: qsTr("压 紧")
            isSelected: Cpp_PLC.M_239

            onButtonPressed: Cpp_PLC.write_into_PLC_Coils(236,true)
            onButtonReleased: Cpp_PLC.write_into_PLC_Coils(236,false)

        }
        A_Button{
            buttonWidth: 250
            buttonHeight: 80
            contentText_Data: qsTr("定 位")

            onButtonPressed: Cpp_PLC.write_into_PLC_Coils(141,true)
            onButtonReleased: Cpp_PLC.write_into_PLC_Coils(141,false)
        }
        A_Button{
            buttonWidth: 250
            buttonHeight: 80
            contentText_Data: Cpp_PLC.M_240 ? qsTr("锯 启") : qsTr("锯 停")
            isSelected: Cpp_PLC.M_240

            onButtonPressed: Cpp_PLC.write_into_PLC_Coils(237,true)
            onButtonReleased: Cpp_PLC.write_into_PLC_Coils(237,false)
        }
        A_Button{
            buttonWidth: 250
            buttonHeight: 80
            contentText_Data: qsTr("锯 切")

            isSelected: Cpp_PLC.M_241

            onButtonPressed: Cpp_PLC.write_into_PLC_Coils(238,true)
            onButtonReleased: Cpp_PLC.write_into_PLC_Coils(238,false)

        }
        A_Button{
            buttonWidth: 250
            buttonHeight: 80
            contentText_Data: qsTr("复 位")

            onButtonPressed: Cpp_PLC.write_into_PLC_Coils(5,true)
            onButtonReleased: Cpp_PLC.write_into_PLC_Coils(5,false)
        }

    }






}
